﻿using System.Xml;
using Microsoft.Xna.Framework.Content.Pipeline;

using TInput = Microsoft.Xna.Framework.Content.Pipeline.Graphics.Texture2DContent;
using TOutput = System.String;

namespace LoA.MapModelProcessor {
	[ContentProcessor(DisplayName = "Model 2of the Map - LoA Framework")]
	public class MapModelProcessorXML : ContentProcessor<TInput, TOutput> {
		public override TOutput Process(TInput input, ContentProcessorContext context) {
			XmlDocument doc = new System.Xml.XmlDocument( );
			XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
			doc.AppendChild(docNode);
			XmlElement root = doc.CreateElement("Map");
			doc.AppendChild(root);
			root.SetAttribute("height", input.Mipmaps[0].Height.ToString( ));
			root.SetAttribute("width", input.Mipmaps[0].Width.ToString( ));
			XmlElement points = doc.CreateElement("Points");
			root.AppendChild(points);

			byte[ ] x = input.Mipmaps[0].GetPixelData( );
			int i = 0;
			XmlElement Xpoint = doc.CreateElement("ERROR");
			XmlElement Xheight = doc.CreateElement("ERROR");
			XmlElement Xwidth = doc.CreateElement("ERROR");
			foreach (byte p in x) {
				int RGBA = i % 4;
				int id = i / 4;
				int height = i / 4 / input.Mipmaps[0].Width;
				int width = i / 4 % input.Mipmaps[0].Width;
				if (RGBA == 0) {
					if (width == 0) {
						Xheight = doc.CreateElement(height.ToString( ));
						root.AppendChild(Xheight);
					}
					Xwidth = doc.CreateElement(width.ToString( ));
					Xheight.AppendChild(Xwidth);
					Xwidth.SetAttribute("id", id.ToString( ));
					Xwidth.SetAttribute("height", (255 - p).ToString( ));
					Xpoint = doc.CreateElement("Point");
					Xpoint.SetAttribute("id", id.ToString( ));
					Xpoint.SetAttribute("pheight", height.ToString( ));
					Xpoint.SetAttribute("pwidth", width.ToString( ));
					Xpoint.SetAttribute("height", (255 - p).ToString( ));
					points.AppendChild(Xpoint);
				}
				i++;
			}
			return doc.OuterXml;
		}
	}
}